import { Component, OnInit, AfterViewInit } from '@angular/core';
import { OrderService } from '@app/services/order/order.service';
import { Router, ActivatedRoute } from '@angular/router';
import { SocketioService } from '@app/services/socketio/socketio.service';
import { storage } from '@app/utils';
import { tableId } from '@app/config';

@Component({
  selector: 'app-start',
  templateUrl: './start.component.html',
  styleUrls: ['./start.component.scss']
})
export class StartComponent implements OnInit, AfterViewInit {
  personNumList: string[] = [];
  remark: string = '';
  personNum: string = '';
  tableId: string = '';
  hasLoading: boolean = true;

  constructor (
    private readonly router: Router,
    private readonly route: ActivatedRoute,
    private readonly orderService: OrderService,
    private readonly socketio: SocketioService,
  ) {
    for (let i = 1; i <= 12; i++) {
      this.personNumList.push(`${i}人`);
    }
    // 获取桌号
    this.tableId = this.route.queryParams['_value'].table_id;
    // 存储到本地
    storage.setItem(tableId, this.tableId);
    // 扫码加入房间
    this.socketio.socket.emit('joinRoom', this.tableId);
    this.getOrderInfo(this.tableId);
  }

  ngOnInit() { }

  // 如果本桌子已经有了点餐信息就直接到首页
  getOrderInfo(tableId: string): void {
    this.orderService.orderInfo$(tableId).subscribe(data => {
      const { code, message, result } = data;
      this.hasLoading = false;
      if (Object.is(code, 0) && result) {
        this.router.navigate(['/home'])
      }
    })
  }

  // 开始点餐
  start(): void {
    console.log('点击了');
    if (this.personNum && this.tableId) {
      const postData = {
        tableId: this.tableId,
        remark: this.remark,
        personNum: this.personNum,
      };
      this.orderService.start$(postData).subscribe(data => {
        const { code, message, result } = data;
        if (Object.is(code, 0)) {
          this.router.navigate(['/home'])
        }
      })
    } else {
      console.log(this.personNum, this.tableId);
    }
  }
  ngAfterViewInit() {
    const that = this;
    // 选择人数的dom操作
    const lisDom: any = document.querySelectorAll('.user_list li');
    for (let i = 0; i < lisDom.length; i++) {
      lisDom[i].onclick = function () {
        for (let j = 0; j < lisDom.length; j++) {
          lisDom[j].className = '';
        }
        this.className = 'active';
        that.personNum = this.querySelector('span').innerHTML.trim();
      }
    }
    // 选择口味的dom操作
    const markLisDom: any = document.querySelectorAll('.mark_list li');
    for (let i = 0; i < markLisDom.length; i++) {
      markLisDom[i].onclick = function () {
        that.remark = '';
        for (let j = 0; j < markLisDom.length; j++) {
          markLisDom[j].className = '';
        }
        this.className = 'active';
        that.remark = this.querySelector('span').innerHTML.trim()
      }
    }
  }
}
